/**
 * Copyright(c) 2014 Xunton Solutions
 *
 * History:
 *   15-9-25 上午9:46 Created by dwzhang
 */
package com.jade.bss.weixin.api.card;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Named;

import com.jade.bss.weixin.WeixinException;
import com.jade.bss.weixin.api.card.protocol.Card;
import com.jade.bss.weixin.api.card.protocol.CreateCardResponse;
import com.jade.bss.weixin.api.card.protocol.StockQuantity;
import com.jade.bss.weixin.api.card.protocol.UploadLogoResponse;
import com.jade.bss.weixin.api.protocol.json.JsonApi;
import com.jade.bss.weixin.api.protocol.json.Response;

/**
 * 卡券相关的接口。
 *
 * @author <a href="mailto:dwzhang@xunton.com">dwzhang</a> 
 * @version 1.0 15-9-25 上午9:46
 */
@Named ("bss_weixinCardApi")
public class CardApi
        extends JsonApi
{
    public static final String URL_UPLOAD_LOGO = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=";
    public static final String URL_CREATE_COUPON = "https://api.weixin.qq.com/card/create?access_token=";
    public static final String URL_MODIFY_STOCK = "https://api.weixin.qq.com/card/modifystock?access_token=";
    public static final String URL_DEL_COUPON = "https://api.weixin.qq.com/card/delete?access_token=";

    public UploadLogoResponse uploadLogo(String token, File logo)
            throws WeixinException
    {
        return postFile(URL_UPLOAD_LOGO + token, "buffer", logo, UploadLogoResponse.class);
    }

    public UploadLogoResponse uploadLogo(String token, InputStream in, String mimeType, String filename)
            throws WeixinException
    {
        return postFile(URL_UPLOAD_LOGO + token, "buffer", in, mimeType, filename,
                UploadLogoResponse.class);
    }

    public CreateCardResponse createCard(String token, Card card)
            throws WeixinException
    {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("card", card);
        return post(URL_CREATE_COUPON + token, params, CreateCardResponse.class);
    }

    public Response modifyStock(String token, String cardId, long num)
            throws WeixinException
    {
        StockQuantity quantity = new StockQuantity();
        quantity.setCardId(cardId);
        if (num < 0) {
            quantity.setDecreaseValue(-num);
        }
        else {
            quantity.setIncreaseValue(num);
        }
        return post(URL_MODIFY_STOCK + token, quantity, Response.class);
    }

    public Response deleteCard(String token, String cardId)
            throws WeixinException
    {
        Map<String, String> params = new HashMap<String, String>();
        params.put("card_id", cardId);
        return post(URL_DEL_COUPON + token, params, Response.class);
    }
}
